package com.uobgroup.ews.uam.web;

import com.uobgroup.ews.uam.core.dao.ldap.LDSDaoImpl;
import com.uobgroup.ews.uam.core.domain.AccessToStaff;
import com.uobgroup.ews.uam.core.model.Group;
import com.uobgroup.ews.uam.core.service.AccessToStaffService;
import com.uobgroup.ews.uam.core.service.SecurityGroupService;
import com.uobgroup.ews.uam.core.service.ldap.LDSServiceImpl;

import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/accesstostaffs")
@Controller
public class AccessToStaffController {

	@Autowired
    AccessToStaffService accessToStaffService;

	@Autowired
    SecurityGroupService securityGroupService;
	
	@Autowired
   private LDSServiceImpl lDsService;
   
   @Autowired
   private ReloadableResourceBundleMessageSource messageSource;

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid AccessToStaff accessToStaff, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
	   
      Group group = lDsService.findGroupByBaseDN(accessToStaff.getName().trim(), LDSDaoImpl.LDAP_DN_GROUP_ACCESSTOSTAFF);
      if (null != group) {
         uiModel.addAttribute("messageError", messageSource.getMessage("exist_security_group_in_lds", new String[] {messageSource.getMessage("label_com_uobgroup_ews_uam_core_domain_accesstostaff", null,null)}, null));
      }
      if (bindingResult.hasErrors() || null != group) {
          populateEditForm(uiModel, accessToStaff);
          return "accesstostaffs/create";
      }
      uiModel.asMap().clear();
      accessToStaffService.saveAccessToStaff(accessToStaff);
      return "redirect:/accesstostaffs/" + encodeUrlPathSegment(accessToStaff.getId().toString(), httpServletRequest);
    }

	@RequestMapping(value = "/create", produces = "text/html", method = RequestMethod.GET)
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new AccessToStaff());
        return "accesstostaffs/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("accesstostaff", accessToStaffService.findAccessToStaff(id));
        uiModel.addAttribute("itemId", id);
        return "accesstostaffs/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("accesstostaffs", accessToStaffService.findAccessToStaffEntries(firstResult, sizeNo));
            float nrOfPages = (float) accessToStaffService.countAllAccessToStaffs() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("accesstostaffs", accessToStaffService.findAllAccessToStaffs());
        }
        return "accesstostaffs/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid AccessToStaff accessToStaff, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, accessToStaff);
            return "accesstostaffs/update";
        }
        uiModel.asMap().clear();
        accessToStaffService.updateAccessToStaff(accessToStaff);
        return "redirect:/accesstostaffs/" + encodeUrlPathSegment(accessToStaff.getId().toString(), httpServletRequest);
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, accessToStaffService.findAccessToStaff(id));
        return "accesstostaffs/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        AccessToStaff accessToStaff = accessToStaffService.findAccessToStaff(id);
        accessToStaffService.deleteAccessToStaff(accessToStaff);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/accesstostaffs";
    }

	void populateEditForm(Model uiModel, AccessToStaff accessToStaff) {
        uiModel.addAttribute("accessToStaff", accessToStaff);
        uiModel.addAttribute("securitygroups", securityGroupService.findAllSecurityGroups());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
